import psycopg2
import os, errno
import sys

PROFILE_PICTURES_BASEDIR = '/findme/profile_pictures'

def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as exc: # Python >2.5
        if exc.errno == errno.EEXIST:
            pass
        else:
            raise


def get_file_id( db ):
    return '234'

def add_user( db, username, password_hash, picture_url=None, email=None ):
    print >> sys.stderr, "adding user %s to db ..." % ( username, )
    return 234

def update_password( db, userid, new_password_hash ):
    pass

def update_picture( db, userid, new_picture_url ):
    pass

def update_email( db, userid, new_email ):
    pass


def get_next_match( db, userid ):
    pass

def indicate_interest( db, userid1, userid2 ):
    pass


def save_image( db, img_contents, ext ):

    # generate a filename
    subdir = time.strftime( "%Y%m%d" )
    imgdir = os.path.join( PROFILE_PICTURES_BASEDIR, subdir )
    mkdir_p( imgdir )
    filename = "%s%s" % ( get_file_id( db ), ext )
    full_path = os.path.join( imgdir, filename )
    with open( full_path, 'wb+' ) as f:
        f.write( img_contents )
    return full_path

